<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="背景：有一个任务非常耗时会消耗后台大量算力，所以在退出页面的时候，要求前端这边发送一个请求来杀死任务。 一开始以为这个需求非常简单，就是在进入其他路由前，发送一下请求，杀死一下任务就好了。 然而现实狠狠的打了我的脸，因为退出页面的场景不止切换路由~ 退出页面场景： 还在本网站，跳到其他路由 刷新页面/关闭页面也需要发送请求来杀死任务  还在本网站，跳到其他路由这个比较简单，在Vue中可以通过路由">
<meta name="keywords" content="js">
<meta property="og:type" content="article">
<meta property="og:title" content="sendBeacon 刷新&#x2F;关闭页面之前发送请求">
<meta property="og:url" content="http://yoursite.com/2019/01/13/刷新-关闭页面之前发送请求/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="背景：有一个任务非常耗时会消耗后台大量算力，所以在退出页面的时候，要求前端这边发送一个请求来杀死任务。 一开始以为这个需求非常简单，就是在进入其他路由前，发送一下请求，杀死一下任务就好了。 然而现实狠狠的打了我的脸，因为退出页面的场景不止切换路由~ 退出页面场景： 还在本网站，跳到其他路由 刷新页面/关闭页面也需要发送请求来杀死任务  还在本网站，跳到其他路由这个比较简单，在Vue中可以通过路由">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1?raw=true">
<meta property="og:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1g0bvkiozjwj30bt04vglt.jpg?raw=true">
<meta property="og:image" content="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1g0bvl43w8gj31gd06n761.jpg?raw=true">
<meta property="og:updated_time" content="2019-07-20T06:55:39.062Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="sendBeacon 刷新&#x2F;关闭页面之前发送请求">
<meta name="twitter:description" content="背景：有一个任务非常耗时会消耗后台大量算力，所以在退出页面的时候，要求前端这边发送一个请求来杀死任务。 一开始以为这个需求非常简单，就是在进入其他路由前，发送一下请求，杀死一下任务就好了。 然而现实狠狠的打了我的脸，因为退出页面的场景不止切换路由~ 退出页面场景： 还在本网站，跳到其他路由 刷新页面/关闭页面也需要发送请求来杀死任务  还在本网站，跳到其他路由这个比较简单，在Vue中可以通过路由">
<meta name="twitter:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/01/13/刷新-关闭页面之前发送请求/"/>





  <title>sendBeacon 刷新/关闭页面之前发送请求 | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/01/13/刷新-关闭页面之前发送请求/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">sendBeacon 刷新/关闭页面之前发送请求</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-13T18:40:18+08:00">
                2019-01-13
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/01/13/刷新-关闭页面之前发送请求/" class="leancloud_visitors" data-flag-title="sendBeacon 刷新/关闭页面之前发送请求">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,963 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1?raw=true" alt=""></p>
<h3 id="背景："><a href="#背景：" class="headerlink" title="背景："></a>背景：</h3><p><strong>有一个任务非常耗时会消耗后台大量算力，所以在退出页面的时候，要求前端这边发送一个请求来杀死任务</strong>。</p>
<p>一开始以为这个需求非常简单，就是在进入其他路由前，发送一下请求，杀死一下任务就好了。</p>
<p>然而现实狠狠的打了我的脸，因为退出页面的场景不止切换路由~</p>
<h3 id="退出页面场景："><a href="#退出页面场景：" class="headerlink" title="退出页面场景："></a>退出页面场景：</h3><ol>
<li>还在本网站，跳到其他路由</li>
<li><strong>刷新页面/关闭页面</strong>也需要发送请求来杀死任务</li>
</ol>
<h3 id="还在本网站，跳到其他路由"><a href="#还在本网站，跳到其他路由" class="headerlink" title="还在本网站，跳到其他路由"></a>还在本网站，跳到其他路由</h3><p>这个比较简单，在<code>Vue</code>中可以通过路由离开的钩子<code>beforeRouteLeave</code>来实现：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">beforeRouteLeave(to, <span class="keyword">from</span>, next) &#123;</span><br><span class="line">   <span class="keyword">if</span> (任务运行中) &#123;</span><br><span class="line">       <span class="comment">// 发送请求</span></span><br><span class="line">   &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">       next(<span class="literal">true</span>) <span class="comment">// 用户离开</span></span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>刷新页面/关闭页面的情况：</strong></p>
<p>然而在刷新页面的时候，<code>beforeRouteLeave</code>并不会执行，接着想到了下面这两个<code>API</code>.</p>
<h2 id="beforeunload和unload"><a href="#beforeunload和unload" class="headerlink" title="beforeunload和unload"></a><code>beforeunload</code>和<code>unload</code></h2><h3 id="beforeunload-当浏览器窗口关闭或者刷新时触发"><a href="#beforeunload-当浏览器窗口关闭或者刷新时触发" class="headerlink" title="beforeunload 当浏览器窗口关闭或者刷新时触发:"></a>beforeunload 当浏览器窗口关闭或者刷新时触发:</h3><p><strong>介绍</strong>：</p>
<p>使用这个<code>API</code>可以阻止页面直接关闭，用户通过点击确定/取消按钮，来决定是否不关闭/刷新当前页面。</p>
<p>在 chrome 下长这个样子，你们肯定都见过：</p>
<p><img src="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1g0bvkiozjwj30bt04vglt.jpg?raw=true" alt=""></p>
<p><strong>如何使用</strong></p>
<p>这个 API 的使用非常简单，只要在页面加载的时候监听一下此事件，在需要出现弹窗的时候<strong>return 一个可以转化为 true 的值</strong>,就可以了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 页面卸载之前</span></span><br><span class="line"><span class="keyword">let</span> killTask = <span class="literal">false</span>; <span class="comment">// 是否杀死任务</span></span><br><span class="line"><span class="built_in">window</span>.onbeforeunload = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (任务运行 &amp;&amp; 对应页面) &#123;</span><br><span class="line">    killTask = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'您可能有数据没有保存'</span>; <span class="comment">// 在部分浏览器可以修改弹窗标题</span></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    killTask = <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 没有return一个可以转化为true的值 就不会出现弹窗</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><strong>出现此弹窗的浏览器行为</strong>：</p>
<p>以下行为是基于 chorme：</p>
<ol>
<li><p>焦点：你没有点击取消/确定之前，焦点会一直在此弹窗上</p>
</li>
<li><p>你无法在出现弹窗的页面上执行任何操作</p>
</li>
<li><p>在其他页面也只能执行简单的点击操作，弹窗还是存在页面中间，无法使用键盘，</p>
</li>
<li><p>键盘：键盘被绑定在弹窗上，只能通过按键<code>Esc</code>、<code>Enter</code>来执行取消/确定操作</p>
</li>
<li><p><strong>弹窗不是页面的 dom，是浏览器的行为</strong></p>
</li>
<li><p><strong>用户取消/确定，没有回调 API，无法得知</strong></p>
</li>
</ol>
<p><strong>弹窗标题</strong>：</p>
<p>chrome 中刷新页面的标题：<code>重新加载此网站?</code></p>
<p>chrome 中关闭页面的标题：<code>离开此网站?</code></p>
<p>现在大部分浏览器都不允许修改弹窗的标题，这个是为了安全考虑，来保证用户不受到错误信息的误导，</p>
<p><strong>迷茫</strong>：</p>
<p>一开始我以为既然可以拦截到用户的刷新/关闭页面的操作，出现了上面那个弹窗，这个需求就已经做完了的时候。</p>
<p>然后发现，<strong>浏览器竟然没有提供用户点击确定/取消刷新页面的回调</strong>。</p>
<p>到这里我陷入了迷茫，盯着<code>beforeunload</code>这个 API 思考了起了人生的意义(其实是在发呆)，盯着盯着，从<code>beforeunload</code>的<code>before</code>我也就想到了<code>unload</code>这个 API。</p>
<p>瞬间又燃起了斗志，何不试试这个<code>unload</code>？</p>
<h3 id="unload当页面正在被卸载的时候触发该事件"><a href="#unload当页面正在被卸载的时候触发该事件" class="headerlink" title="unload当页面正在被卸载的时候触发该事件"></a><code>unload</code>当页面正在被卸载的时候触发该事件</h3><p><strong>介绍</strong></p>
<p>当页面正在被卸载的时候触发该事件，该事件不可取消，为不可逆操作。</p>
<p><strong>使用</strong></p>
<p>直接监听该事件就可以了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onunload = <span class="function"><span class="params">e</span> =&gt;</span> &#123;&#125;</span><br></pre></td></tr></table></figure>
<p><strong>结合需求</strong>:</p>
<p><code>killTask</code>为<code>beforeunload</code>时定义的变量，每次进入回调，都会给<code>killTask</code>赋值，使用这个值就可以判断什么时候可以发送请求杀死任务。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onunload = <span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (killTask &amp;&amp; 对应页面) &#123;</span><br><span class="line">    <span class="comment">// 发送请求</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>到这里大家肯定以为已经做出来了该需求，事实上，并没有！</p>
<p><strong>无法发送异步请求</strong></p>
<p>我使用的是<code>axios</code>来发送请求，请求发出去了，但是被取消了，服务器那边根本没有收到请求，如下。</p>
<p><img src="https://github.com/OBKoro1/articleImg_src/blob/master/weibo_img_move/005Y4rCogy1g0bvl43w8gj31gd06n761.jpg?raw=true" alt=""></p>
<p>经过一顿分析:发现是<code>axios</code>请求是异步的问题，谷歌之后发现axios不支持同步的请求</p>
<p><strong>最后使用原生的<a href="http://www.w3school.com.cn/xml/xml_http.asp" target="_blank" rel="noopener">XMLHttpRequest</a>对象</strong>，让请求同步</p>
<p><del>大功告成！</del> 实际上，上面才是我第一次要发的内容，而下面更好的解决方法！</p>
<h2 id="缺陷与更好的建议："><a href="#缺陷与更好的建议：" class="headerlink" title="缺陷与更好的建议："></a>缺陷与更好的建议：</h2><p>当我把这篇文章发布在公众号上，被<a href="https://mp.weixin.qq.com/s/3taWHBu0vxRXP7WDax5M-Q" target="_blank" rel="noopener">奇舞周刊</a>转载了，上面一些大佬给我提了一些建议。</p>
<p>研究了一下，结果…好吧！我承认我是菜鸡。</p>
<p>hey~ 不过这正是我写博客的收获之一，分享经验，收获知识！</p>
<h3 id="性能缺陷："><a href="#性能缺陷：" class="headerlink" title="性能缺陷："></a>性能缺陷：</h3><p>XHR同步请求会阻碍页面卸载，如果是刷新/跳转页面的话，<strong>页面重新展示速度会变慢，导致性能问题</strong>。</p>
<p>毕竟<strong>向网络发送请求并获得响应可能会超级慢</strong>，有可能是用户网络环境比较差，又或者是服务器挂了，请求一直没返回回来…</p>
<p>基于性能问题，大佬们推荐<strong>使用Beacon代替XHR</strong>，然后经过一番搜索…</p>
<h3 id="Beacon-API"><a href="#Beacon-API" class="headerlink" title="Beacon API"></a>Beacon API</h3><ol>
<li><strong>Beacon API用于将少量数据通过post请求发送到服务器</strong>。</li>
<li><strong><code>Beacon</code>是非阻塞请求，不需要响应</strong></li>
</ol>
<h4 id="完美解决性能缺陷问题："><a href="#完美解决性能缺陷问题：" class="headerlink" title="完美解决性能缺陷问题："></a>完美解决性能缺陷问题：</h4><ol>
<li><strong>浏览器将 <code>Beacon</code> 请求排队让它在空闲的时候执行并立即返回控制</strong></li>
<li>它在<code>unload</code>状态下也可以异步发送，不阻塞页面刷新/跳转等操作。</li>
</ol>
<p>所以<strong><code>Beacon</code>可以完美解决上面提到的因XHR同步请求阻塞而引起的性能缺陷问题</strong>。</p>
<h4 id="使用：navigator-sendBeacon"><a href="#使用：navigator-sendBeacon" class="headerlink" title="使用：navigator.sendBeacon()"></a>使用：<code>navigator.sendBeacon()</code></h4><p><strong>完整API</strong>：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> result = navigator.sendBeacon(url, data);</span><br></pre></td></tr></table></figure>
<p><code>Beacon</code>是挂在<code>navigator</code>下面的，上面就是它的完整API。</p>
<p><code>result</code>是一个布尔值，代表这次发送请求的结果:</p>
<ul>
<li>如果浏览器接受并且把请求排队了则返回 tru</li>
<li>如果在这个过程中出现了问题就返回 false</li>
</ul>
<p><code>navigator.sendBeacon</code>接受两个参数：</p>
<ol>
<li>url: 请求的 URL。请求是 POST 请求。</li>
<li>data: 要发送的数据。 数据类型可以是：ArrayBufferView, Blob,  FormData，Sting。</li>
</ol>
<p>来看一个用<code>FormData</code>来传递数据的栗子，你就懂了：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建一个新的 FormData 并添加一个键值对</span></span><br><span class="line"><span class="keyword">let</span> data = <span class="keyword">new</span> FormData();</span><br><span class="line">data.append(<span class="string">'hello'</span>, <span class="string">'world'</span>);</span><br><span class="line"><span class="keyword">let</span> result = navigator.sendBeacon(<span class="string">'./src'</span>, data);</span><br><span class="line"><span class="keyword">if</span> (result) &#123; </span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'请求成功排队 等待执行'</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'失败'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="浏览器支持："><a href="#浏览器支持：" class="headerlink" title="浏览器支持："></a>浏览器支持：</h4><p>浏览器支持：Edge：14+，Firefox：31+，Chrome：39+，Opera：26+，IE：不支持。</p>
<p>虽然现在浏览器对<code>sendBeacon</code>的支持很好，我们对其做一下兼容性处理也是有必要的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (navigator.sendBeacon) &#123;</span><br><span class="line">  <span class="comment">// Beacon 代码</span></span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line"> <span class="comment">// 回退到 XHR同步请求或者不做处理</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="web-wroker中使用Beacon"><a href="#web-wroker中使用Beacon" class="headerlink" title="web wroker中使用Beacon"></a>web wroker中使用Beacon</h4><p>因为<code>Beacon</code>是挂在<code>navigator</code>下面，而web worker也有<code>navigator</code>，去找了一下，真的给我找到了。</p>
<p>这儿有一个MDN提供的<a href="https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API/Using_the_Beacon_API#WorkerNavigator.sendBeacon(" target="_blank" rel="noopener">栗子</a>)，可以点进去看一下。</p>
<p>PS：对web worker不熟悉的同学可以看我这篇<a href="https://juejin.im/post/5bf8fa045188252f170e0dcb" target="_blank" rel="noopener">文章</a></p>
<h4 id="Beacon其他相关"><a href="#Beacon其他相关" class="headerlink" title="Beacon其他相关"></a>Beacon其他相关</h4><ul>
<li><strong>客户端优化：可以将 Beacon 请求合并到其他请求上，一同处理</strong>, 尤其在移动环境下。</li>
<li><strong>Beacon更多的情况是用于做前端埋点，监控用户活动</strong>，它的初衷也基于此。</li>
</ul>
<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>本文总共讲了三个API，<code>beforeunload</code>、<code>unload</code>和<code>Beacon</code>，<code>Beacon</code>这个API估计知道的人比较少，以后遇到前端埋点和页面卸载前发送请求的需求，记得使用这三个API。</p>
<p>以上2019.02.19</p>
<p><a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="http://obkoro1.com/web_accumulate/accumulate/" target="_blank" rel="noopener">前端积累文档</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a>、<a href="https://github.com/OBKoro1" target="_blank" rel="noopener">GitHub</a></p>
<p>参考资料：</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API/Using_the_Beacon_API" target="_blank" rel="noopener">MDN</a></p>
<p><a href="https://www.barretlee.com/blog/2016/02/20/navigator-beacon-api/" target="_blank" rel="noopener">页面跳转时，统计数据丢失问题探讨</a></p>
<p><a href="https://juejin.im/post/5b694b5de51d4519700fa56a#heading-4" target="_blank" rel="noopener">使用 Web Beacon API 记录活动</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/01/Vuex-的使用入门-极简使用/" rel="next" title="Vuex的使用入门-极简使用">
                <i class="fa fa-chevron-left"></i> Vuex的使用入门-极简使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/02/19/H5-notification浏览器桌面通知/" rel="prev" title="H5 notification浏览器桌面通知">
                H5 notification浏览器桌面通知 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#背景："><span class="nav-number">1.</span> <span class="nav-text">背景：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#退出页面场景："><span class="nav-number">2.</span> <span class="nav-text">退出页面场景：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#还在本网站，跳到其他路由"><span class="nav-number">3.</span> <span class="nav-text">还在本网站，跳到其他路由</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#beforeunload和unload"><span class="nav-number"></span> <span class="nav-text">beforeunload和unload</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#beforeunload-当浏览器窗口关闭或者刷新时触发"><span class="nav-number">1.</span> <span class="nav-text">beforeunload 当浏览器窗口关闭或者刷新时触发:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unload当页面正在被卸载的时候触发该事件"><span class="nav-number">2.</span> <span class="nav-text">unload当页面正在被卸载的时候触发该事件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缺陷与更好的建议："><span class="nav-number"></span> <span class="nav-text">缺陷与更好的建议：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#性能缺陷："><span class="nav-number">1.</span> <span class="nav-text">性能缺陷：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Beacon-API"><span class="nav-number">2.</span> <span class="nav-text">Beacon API</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#完美解决性能缺陷问题："><span class="nav-number">2.1.</span> <span class="nav-text">完美解决性能缺陷问题：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用：navigator-sendBeacon"><span class="nav-number">2.2.</span> <span class="nav-text">使用：navigator.sendBeacon()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#浏览器支持："><span class="nav-number">2.3.</span> <span class="nav-text">浏览器支持：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#web-wroker中使用Beacon"><span class="nav-number">2.4.</span> <span class="nav-text">web wroker中使用Beacon</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Beacon其他相关"><span class="nav-number">2.5.</span> <span class="nav-text">Beacon其他相关</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小结"><span class="nav-number"></span> <span class="nav-text">小结</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

